/*
 *  Copyright (C) 2010:
 *                 Buzzanca Marco <marco.bzn@gmail.com>
 *         Monaco Davide Giuseppe <black.ralkass@gmail.com>
 *              Petralia Veronica <veronicapetralia@gmail.com>
 *
 * This file is part of DS2011BMP
 *
 * DS2011BMP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DS2011BMP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 *
 * NOTE: this file should not be included directly,
 *       Include udpserver.h instead.
 */

/**
 * @file udpserver.cpp
 * @author Marco Buzzanca
 *
 * This file contains UDPServer class declaration and implementation.
 */

#include <boost/asio.hpp>
#include <boost/cstdint.hpp>
#include <boost/shared_ptr.hpp>
#include "udpinterface.h"
#include "address.h"

/**
 * UDP Server
 *
 * Basic implementation of an UDP Server. First, it is required to bind the
 * server to a specified port, either in construction step, or later with the
 * bind() method. After that, the server is ready to accept client requests, and
 * the receive() method should be called. Response should be sent with the
 * send() method.
 */
class UDPServer : public UDPSenderReceiver
{
private:
    /**
     * @brief udp::socket shared pointer typedef.
     */
    typedef boost::shared_ptr<boost::asio::ip::udp::socket> SocketPointer;

    /**
     * @brief Provides basic I/O services.
     */
    boost::asio::io_service _io_service;

    /**
     * @brief Communication endpoint.
     */
    boost::asio::ip::udp::endpoint _endpoint;

    /**
     * @brief Noncopyable, it must be handled with pointers.
     */
    SocketPointer _socket;

    /**
     * @brief Port used to accept incoming connections.
     */
    boost::uint16_t _port;

public:
    /**
     * Responder
     *
     * This is a concrete implementation of UDPSender. It should be created
     * by UDP Servers in multi-threaded environments, where the server is
     * supposed to serve more than one client, hence responses might be sent
     * using multiple endpoints.
     */
    class Responder : public UDPSenderReceiver
    {
    private:
        /**
         * @brief boost::int8_t shared pointer typedef.
         */
        typedef boost::shared_ptr<char> BufferPointer;

        /**
         * @brief Communication endpoint.
         */
        boost::asio::ip::udp::endpoint _endpoint;

        /**
         * @brief UDP Socket received from server.
         */
        SocketPointer _socket;

        /**
         * @brief Request buffer.
         */
        BufferPointer _buffer;

        /**
         * @brief Request length.
         */
        size_t _request_length;

        /**
         * @brief Receives requests over UDP from the requesting client.
         *
         * @note Will only be used internally.
         */
        size_t receive(char* dest_buf, size_t buf_len)
        {
            return _socket->receive_from
                (boost::asio::buffer(dest_buf, buf_len), _endpoint);
        }

        /**
         * @brief Receives a size_t type over UDP from the requesting client.
         *
         * @note Will only be used internally.
         */
        size_t receive(size_t& size)
        {
            return _socket->receive_from
                (boost::asio::buffer(&size, sizeof(size_t)), _endpoint);
        }

        /**
         * @brief Receives a buffer over UDP from clients.
         *
         * @note MutableBufferSequence must abide to certain rules, see boost
         * documentation. Will only be used internally.
         */
        template <typename MutableBufferSequence>
        size_t receive(MutableBufferSequence& buf_seq)
        {
            return _socket->receive_from(buf_seq, _endpoint);
        }

    public:
        /**
         * @brief Constructor, should only be built by UDPServer.
         */
        Responder(const boost::asio::ip::udp::endpoint& endpoint,
                  const SocketPointer& socket, const char* buffer,
                  size_t request_length)
        : _endpoint(endpoint), _socket(socket), _request_length(request_length)
        {
            _buffer = BufferPointer(new char[_request_length]);
            memcpy(_buffer.get(), buffer, _request_length);
        }

        /**
         * @brief Sends response over UDP to the requesting client.
         */
        size_t send(char* src_buf, size_t buf_len)
        {
            return _socket->send_to(boost::asio::buffer(src_buf, buf_len),
                                    _endpoint);
        }

        /**
         * @brief Sends a size_t type over UDP to the requesting client.
         */
        size_t send(const size_t& size)
        {
            return _socket->send_to(boost::asio::buffer(&size, sizeof(size_t)),
                                    _endpoint);
        }

        /**
         * @brief Sends a string over UDP to the requesting client.
         */
        size_t send(const std::string& str)
        {
            return _socket->send_to(boost::asio::buffer(str), _endpoint);
        }

        /**
         * @brief Sends a buffer over UDP to the requesting client.
         *
         * @note ConstBufferSequence must abide to certain rules, see boost
         * documentation.
         */
        template <typename ConstBufferSequence>
        size_t send(const ConstBufferSequence& buf_seq)
        {
            return _socket->send_to(buf_seq, _endpoint);
        }

        /**
        * @brief Gets internal buffer.
        */
        const char* getBuffer() const
        { return _buffer.get(); }

        /**
        * @brief Gets internal buffer length.
        */
        size_t getRequestLength() const
        { return _request_length; }

        /**
        * @brief Unserializes data from internal buffer.
        *
        * @note An object is serializable if it has a serialize() private method.
        *       See boost::serialize documentation.
        *
        * @param obj the Object which will receive unserialization data.
        */
        template <typename Serializable>
        Responder& operator >> (Serializable& obj)
        {
            // stringstream used to unserialize
            std::stringstream iss;
            iss.write(_buffer.get(), _request_length);

            boost::archive::text_iarchive ia(iss);

            // writes into provided object content of textarchive.
            ia >> obj;

            return (*this);
        }

    };

    // TODO: Two step construction for socket. Creation, opening and binding.

    /**
     * @brief Default constructor.
     */
    UDPServer() : _io_service() { }

    /**
     * @brief Sets server port.
     */
    UDPServer(boost::uint16_t port)
    : _io_service(), _port(port) { }

    /**
     * @brief Sets server port from specified Address object.
     */
    UDPServer(const Address& address)
    : _io_service(), _port(address.getPort()) { }

    /**
     * @brief Destructor.
     */
    ~UDPServer() { }

    /**
     * @brief Gets server port.
     */
    boost::uint16_t getPort() const
    {
        return _port;
    }

    /**
     * @brief Sets server port.
     */
    void setPort(boost::uint16_t port)
    {
        _port = port;
    }

    /**
     * @brief Binds server to previously specified port.
     */
    void bind()
    {
        using boost::asio::ip::udp;

        _socket = SocketPointer
            (new udp::socket(_io_service, udp::endpoint(udp::v4(), _port)));
    }

    /**
     * @brief Binds server to specified port.
     */
    void bind(boost::uint16_t port)
    {
        setPort(port);
        bind();
    }

    /**
     * @brief Sends response over UDP to the requesting client.
     */
    size_t send(char* src_buf, size_t buf_len)
    {
        return _socket->send_to(boost::asio::buffer(src_buf, buf_len),
                                _endpoint);
    }

    /**
     * @brief Sends a size_t type over UDP to the requesting client.
     */
    size_t send(const size_t& size)
    {
        return _socket->send_to(boost::asio::buffer(&size, sizeof(size_t)),
                                _endpoint);
    }

    /**
     * @brief Sends a string over UDP to the requesting client.
     */
    size_t send(const std::string& str)
    {
        return _socket->send_to(boost::asio::buffer(str), _endpoint);
    }

    /**
     * @brief Sends a buffer over UDP to the requesting client.
     *
     * @note ConstBufferSequence must abide to certain rules, see boost
     * documentation.
     */
    template <typename ConstBufferSequence>
    size_t send(const ConstBufferSequence& buf_seq)
    {
        return _socket->send_to(buf_seq, _endpoint);
    }

    /**
     * @brief Receives requests over UDP from clients.
     */
    size_t receive(char* dest_buf, size_t buf_len)
    {
        return _socket->receive_from(boost::asio::buffer(dest_buf, buf_len),
                                     _endpoint);
    }

    /**
     * @brief Receives a size_t type over UDP from clients.
     */
    size_t receive(size_t& size)
    {
        return _socket->receive_from(boost::asio::buffer(&size, sizeof(size_t)),
                                     _endpoint);
    }

    /**
     * @brief Receives a buffer over UDP from clients.
     *
     * @note MutableBufferSequence must abide to certain rules, see boost
     * documentation.
     */
    template <typename MutableBufferSequence>
    size_t receive(MutableBufferSequence& buf_seq)
    {
        return _socket->receive_from(buf_seq, _endpoint);
    }

    /**
     * @brief Receives data over UDP and returns responder object.
     *
     * Use this in multi-threaded environments when the server is supposed
     * to serve more than one client.
     */
    Responder receive()
    {
        char buffer[MAX_BUF_LEN];

        size_t request_length = _socket->receive_from
            (boost::asio::buffer(buffer, MAX_BUF_LEN), _endpoint);

        return Responder(_endpoint, _socket, buffer, request_length);
    }

};
